package org.study.es.boot.controller;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.study.es.boot.entity.ArticleEntity;
import org.study.es.boot.service.ArticleService;

import java.util.List;

/**
 * 参考 https://segmentfault.com/a/1190000041201015
 *
 * @author Administrator
 * @date 2021-12-30
 */
@Slf4j
@Controller
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private ArticleService articleService;

    @GetMapping(value = "/toSearch")
    public String toSearchPage() {
        return "search";
    }

    @ResponseBody
    @GetMapping("/findById/{id}")
    public ArticleEntity findById(@PathVariable(name = "id", required = true) long id) {
        ArticleEntity articleEntity = articleService.findById(id);
        return articleEntity;
    }

    @ResponseBody
    @DeleteMapping("/deleteById/{id}")
    public boolean deleteById(@PathVariable(name = "id", required = true) long id) {
        Boolean delete = articleService.deleteById(id);
        return delete;
    }

    @ResponseBody
    @PostMapping("/save")
    public ArticleEntity save(@RequestBody ArticleEntity article) {
        ArticleEntity save = articleService.save(article);
        return save;
    }

    @GetMapping("/search")
    public String search(Model model, @RequestParam(name = "keyword", required = true) String keyword) {
        log.info("调用 query() 方法，请求参数：{}", keyword);
        Iterable<ArticleEntity> list = articleService.search(keyword);
        model.addAttribute("list", list);
        return "search-result";
    }
}
